package com.lagou.es.controller;

import com.lagou.common.pojo.ProductES;
import com.lagou.common.pojo.ProductVO;
import com.lagou.common.pojo.Products;
import com.lagou.es.resultmapper.ESSearchResultMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilter;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/search")
public class ESController {

    @Autowired
    private ElasticsearchTemplate template;

    @GetMapping("/query")
    public Map queryProductsByPage(@RequestBody ProductVO productVO) {

        System.out.println(productVO);
        //1 构建原生查询器
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        //2 source过滤
        queryBuilder.withSourceFilter(new FetchSourceFilter(new String[0], new String[0]));
        //3 查询条件
        //3.1 姓名
        queryBuilder.withQuery(QueryBuilders.matchQuery("name", productVO.getName()));

        //3.2分页和排序
        queryBuilder.withPageable(PageRequest.of(productVO.getCurrentPage() - 1, productVO.getPageSize(), Sort.by(Sort.Direction.ASC, "price")));

        //3.3高亮
        HighlightBuilder.Field field = new HighlightBuilder.Field("name");

        field.preTags("<font style='color:red'>");
        field.postTags(" </font>");
        queryBuilder.withHighlightFields(field);

        //3.4 对查询结果价格进行范围过滤
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price").gte(productVO.getMinPrice()).lte(productVO.getMaxPrice());
//        rangeQuery.gte(productVO.getMinPrice());
//        rangeQuery.lte(productVO.getMaxPrice());
        queryBuilder.withFilter(rangeQuery);

        //执行查询
        AggregatedPage<ProductES> result = template.queryForPage(queryBuilder.build(), ProductES.class, new ESSearchResultMapper());

        HashMap<Object, Object> map = new HashMap<>();
        if (result != null){
            long total = result.getTotalElements();
            int size = result.getSize();
            List<ProductES> content = result.getContent();
            for (ProductES productES : content) {
                System.out.println(productES);
            }
            map.put("total",total);
            map.put("size",size);
            map.put("content",content);
        }else {
            map.put("msg","无匹配结果");
        }
        return map;
    }
}
